﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      Role Management Page
// Created By:     Miles Chen (milesch@wicresoft.com)
// Created Date:   2011-2-26
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASBCC.Business;
using ASBCC.Database.EntityFramework;

namespace ASB.CC.Web.Admin
{
    public partial class RoleManagement2 : EntityPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected IEnumerable GetBelongsToList()
        {
            return new string[] { "--请选择--" }.Concat(Enum.GetNames(typeof(SystemModule)));
        }

        protected IEnumerable GetMenus(object dataItem)
        {
            var menus = dataItem as IEnumerable<ASBCC.Database.EntityFramework.Menu>;
            var raw = from t in menus
                      where !t.Disabled
                      orderby t.Sort
                      select new
                      {
                          Menu = t,
                          Level = RoleManagementHelper.GetLevel(t),
                      };

            var h2 = from t in raw.ToArray()
                     where t.Level == 3
                     select t.Menu.Parent;

            foreach (var m in h2.Distinct())
            {
                yield return new
                {
                    m.Name,
                    m.Description,
                    Children = from t in menus
                               where t.Parent != null && t.Parent.MenuID == m.MenuID && !t.Disabled
                               orderby t.Sort
                               select t,
                };
            }
        }

        protected IEnumerable GetMenuRelation(object dataItem, object module)
        {
            string belongsTo = module as string;

            using (var dc = new CCEntities())
            {
                var raw = from t in dc.Menus
                          where !t.Disabled && t.BelongsTo == belongsTo
                          orderby t.Sort
                          select t;

                var h2 = from t in raw.ToArray()
                         where RoleManagementHelper.GetLevel(t) == 2
                         select t;

                if (dataItem == null)
                {
                    foreach (var m in h2)
                    {
                        m.Children.Load();
                        yield return new
                        {
                            m.Name,
                            m.Description,
                            Children = from t in m.Children
                                       where !t.Disabled
                                       orderby t.Sort
                                       select t,
                        };
                    }
                }
                else
                {
                    var menus = dataItem as IEnumerable<ASBCC.Database.EntityFramework.Menu>;
                    var ids = menus.Select(p => p.MenuID);
                    var source = from t in h2
                                 select new
                                 {
                                     t.Name,
                                     t.Description,
                                     Children = from m in t.Children
                                                where !m.Disabled
                                                orderby m.Sort
                                                select new
                                                {
                                                    m.MenuID,
                                                    m.Name,
                                                    m.Description,
                                                    Checked = ids.Contains(m.MenuID) ? "checked" : "",
                                                },
                                 };
                    foreach (var m in source)
                    {
                        yield return m;
                    }
                }
            }
        }

        protected IEnumerable GetModules()
        {
            return Enum.GetNames(typeof(SystemModule));
        }

        protected IEnumerable GetModules(object data)
        {
            return Enum.GetNames(typeof(SystemModule)).Select(p => new
            {
                Module = p,
                Data = data,
            });
        }

        protected IEnumerable GetPages(object dataItem)
        {
            var pages = dataItem as IEnumerable<ASBCC.Database.EntityFramework.AspxPage>;
            return from t in pages
                   where !t.Disabled
                   select t;
        }

        protected IEnumerable GetPageRelation(object dataItem, object module)
        {
            string belongsTo = module as string;

            using (var dc = new CCEntities())
            {
                var raw = from t in dc.AspxPages
                          where !t.Disabled && t.BelongsTo == belongsTo
                          select t;

                if (dataItem == null)
                {
                    return raw.ToArray();
                }
                else
                {
                    var pages = dataItem as IEnumerable<ASBCC.Database.EntityFramework.AspxPage>;
                    var ids = pages.Select(p => p.PageID);
                    var source = from t in raw.ToArray()
                                 select new
                                 {
                                     t.PageID,
                                     t.FullName,
                                     t.AccessLevel,
                                     Checked = ids.Contains(t.PageID) ? "checked" : "",
                                 };
                    return source.ToArray();
                }
            }
        }

        protected IEnumerable GetPCATRelation(object dataItem)
        {
            using (var dc = new CCEntities())
            {
                var raw = from t in dc.PCATs
                          where !t.Province.Disabled && !t.Category.Disabled
                          select new
                          {
                              t.ProvinceID,
                              CategoryID = t.CateID,
                              ProvinceName = t.Province.Name,
                              CategoryName = t.Category.Name,
                          };

                if (dataItem == null)
                {
                    return raw.ToArray();
                }
                else
                {
                    var pcats = dataItem as IEnumerable<ASBCC.Database.EntityFramework.PCAT>;
                    var ids = pcats.Select(p => p.ProvinceID + ";" + p.CateID);
                    var source = from t in raw.ToArray()
                                 select new
                                 {
                                     t.ProvinceID,
                                     t.CategoryID,
                                     t.ProvinceName,
                                     t.CategoryName,
                                     Checked = ids.Contains(t.ProvinceID + ";" + t.CategoryID) ? "checked" : "",
                                 };
                    return source;
                }
            }
        }

        protected IEnumerable GetCountryRelation(object dataItem)
        {
            using (var dc = new CCEntities())
            {
                var raw = from t in dc.Countries
                          where !t.Disabled
                          select t;

                if (dataItem == null)
                {
                    foreach (var t in raw)
                    {
                        t.Areas.Load();
                        yield return t;
                    }
                }
                else
                {
                    var countries = dataItem as IEnumerable<ASBCC.Database.EntityFramework.Country>;
                    var ids = countries.Select(p => p.CountryID);
                    foreach (var t in raw.ToArray())
                    {
                        t.Areas.Load();
                        yield return new
                        {
                            t.CountryID,
                            t.Name,
                            t.Areas,
                            Checked = ids.Contains(t.CountryID) ? "checked" : "",
                        };
                    }
                }
            }
        }
        protected IEnumerable GetPCATs(object dataItem)
        {
            var pcats = dataItem as IEnumerable<ASBCC.Database.EntityFramework.PCAT>;
            foreach (var t in pcats)
            {
                t.ProvinceReference.Load();
                t.CategoryReference.Load();
                if (!t.Category.Disabled && !t.Province.Disabled)
                    yield return new
                    {
                        ProvinceName = t.Province.Name,
                        CategoryName = t.Category.Name,
                    };
            }
        }

        protected IEnumerable GetCountries(object dataItem)
        {
            var countries = dataItem as IEnumerable<ASBCC.Database.EntityFramework.Country>;
            foreach (var t in countries)
            {
                if (!t.Disabled)
                {
                    t.Areas.Load();
                    yield return t;
                }
            }
        }
        protected IEnumerable GetAreas(object dataItem)
        {
            var areas = dataItem as IEnumerable<ASBCC.Database.EntityFramework.Area>;
            return from t in areas
                   where !t.Disabled
                   select t;
        }

        protected override EntityDataSource EntitySource
        {
            get { return edsMain; }
        }

        protected override GridView EntityGrid
        {
            get { return gvMain; }
        }

        protected override DetailsView EntityDetails
        {
            get { return dvMain; }
        }

        protected override TextBox EntitySearchTxt
        {
            get { return txtSearch; }
        }

        protected override Button EntityAddBtn
        {
            get { return btnAdd; }
        }

        protected override Button EntityClearBtn
        {
            get { return btnClear; }
        }

        protected override Button EntitySearchBtn
        {
            get { return btnSearch; }
        }

        protected override string GetEntityWhereExpression(string keyword)
        {
            return "(it.Name like N'%" + keyword + "%' and it.Description!='+pcat+' and it.Description!='+country+')";
        }

        protected override void OnEntityDisabling(int entityKey)
        {
            RoleManagementHelper.SetRoleDisabled(entityKey);
            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.Admin, "RoleManagement disabled: id=" + entityKey + "; name=" + RoleManagementHelper.getName(entityKey));
        }


        protected override void OnEntityInserting(EntityDataSourceChangingEventArgs e)
        {
            var dc = e.Context;
            var role = e.Entity as Role;

            InternalUpdateRole(dc, role);
        }

        protected override void OnEntityUpdating(EntityDataSourceChangingEventArgs e)
        {
            var dc = e.Context;
            var role = e.Entity as Role;

            role.AspxPages.Load();
            role.AspxPages.Clear();

            role.Menus.Load();
            role.Menus.Clear();

            role.Countries.Load();
            role.Countries.Clear();

            role.PCATs.Load();
            role.PCATs.Clear();

            InternalUpdateRole(dc, role);
        }

        private void InternalUpdateRole(System.Data.Objects.ObjectContext dc, Role role)
        {
            var pages = this.Request.Form["pagecheck"];
            var menus = this.Request.Form["menucheck"];
            var pcatcheck = this.Request.Form["pcatcheck"];
            var countries = this.Request.Form["countrycheck"];

            RoleManagementHelper.InternalUpdateRole(dc, role, pages, menus, pcatcheck, countries);
        }

        protected void EntityRoles_Inserted(object sender, EntityDataSourceChangedEventArgs e)
        {
            var dc = e.Context;
            var role = e.Entity as Role;

            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.Admin, "RoleManagement inserted. id=" + role.RoleID + "; name=" + role.Name + "; description=" + role.Description + "; belongsTo=" + role.BelongsTo + "; isAdmin=" + role.IsAdmin);
        }

        protected void EntityRoles_Updated(object sender, EntityDataSourceChangedEventArgs e)
        {
            var dc = e.Context;
            var role = e.Entity as Role;

            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.Admin, "RoleManagement updated. id=" + role.RoleID + "; name=" + role.Name + "; description=" + role.Description + "; belongsTo=" + role.BelongsTo + "; isAdmin=" + role.IsAdmin);
        }
        /// <summary>
        /// 通过IsAdmin取yes/NO
        /// </summary>
        protected string GetIsAdmin(object isAdmin)
        {
            if (isAdmin == null)
                return "";
            if (Convert.ToBoolean(isAdmin) == true)
                return "Yes";
            if (Convert.ToBoolean(isAdmin) == false)
                return "No";
            return "";
        }
    }
}
